//
//  UserAccount.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/8/15.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit

class UserAccount: NSObject {

    class func login(withUsername username: String, password pwd: String, displayViewController dvc: UIViewController, complection: @escaping (String)->()) {
        
        ProgressHUD.show(withStatus: "登录中...")
        var urlString = Base_url + Login_url
        urlString = urlString + "?login_username=" + username + "&login_password=" + pwd
        let userDefault = UserDefaults.standard
        
        NetworkTools.shareInstance.requestData(urlString, .get, [:]) { (result, isSuccess) in
            
            if isSuccess == true {
            
                guard let json = result as? [String: Any] else { return }
                if (json["success"]! as AnyObject).integerValue == 1 {
                    complection("登录成功")
                    ProgressHUD.dismiss()
//                    DZYLog(json)
                    let type = json["type"] as! Int
//                    UserDefaults.User.store(type, forkey: .bussinessType)
                    userDefault.set(type, forKey: "bussinessType")
                    userDefault.synchronize()
                    if type == 1 { // 是技师
                        NotificationCenter.default.post(name: Notification.Name(rawValue: "ISLOGIN"), object: true)
                        dvc.dismiss(animated: true, completion: nil)
                        return
                    }
                    
                    guard let dict = json["data"] as? [String: Any] else { return }
                    let dict2 = dict["store_id"] as! Int
                    let style = json["check_status"] as! Int
                    let storeInfo: [String: Int] = ["storeID": dict2, "style": style]
                    userDefault.set(storeInfo, forKey: "storeID")
                    userDefault.synchronize()
                    
                    let status = json["check_status"] as! Int
                    if status == 2 {
                        // 审核通过 进入主页
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ISLOGIN"), object: true)
                        userDefault.setValue("2", forKey: "check_status")
                        userDefault.synchronize()
                        dvc.dismiss(animated: true, completion: nil)
                    } else if status == 1 {
                        // 正在审核 不能进入主页
                        userDefault.setValue("1", forKey: "check_status")
                        userDefault.synchronize()
                        
                    } else if status == 3 {
                        let vc = RegisterViewController()
                        vc.pushStr = "fromLogin"
                        userDefault.setValue("3", forKey: "check_status")
                        userDefault.synchronize()
                        let navi = UINavigationController(rootViewController: vc)
                        dvc.present(navi, animated: true, completion: nil)
                    } else if status == 4 {
                        // 审核中 可以进入主页
                        userDefault.setValue("4", forKey: "check_status")
                        userDefault.synchronize()
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ISLOGIN"), object: true)
                        dvc.dismiss(animated: true, completion: nil)
                    } else if status == 5 {
                        // 修改资料被拒绝 可以进入主页
                        userDefault.setValue("5", forKey: "check_status")
                        userDefault.synchronize()
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ISLOGIN"), object: true)
                        dvc.dismiss(animated: true, completion: nil)
                    }
                } else {
                    let message = json["msg"] as! String
                    complection(message)
                    ProgressHUD.showError(withStatus: message)
                }
                
            } else {
                ProgressHUD.dismiss()
                ProgressHUD.showError(withStatus: "登录失败 未获取到数据")
                complection("登录失败")
            }
        }
    }
    
    class func saveAccount(withUsername username: String, password pwd: String, isRememberPassword: Bool = true) {
        
//        let userDefault = UserDefaults.standard
        let dict = [username: pwd]
//        userDefault.set(dict, forKey: "userinfo")
        UserDefaults.User.store(dict, forkey: .userInfo)
        
        DZYLog(dict)
        if isRememberPassword == false {
            let tempDict = [username: ""]
            UserDefaults.User.store(tempDict, forkey: .userInfo)
//            userDefault.setValue(tempDict, forKey: "userinfo")
        }
//        userDefault.synchronize()
    }
    
    fileprivate class func checkStatus(on dvc: UIViewController) {
        ProgressHUD.show(withStatus: "获取审核信息...")
        
        let urlString = Base_url + Check_state_url
        NetworkTools.shareInstance.requestData(urlString, .get, [:]) { (result, isSuccess) in
            
            if isSuccess == false {
                ProgressHUD.showInfo(withStatus: "网络错误 请重试")
                return
            }
            
            guard let json = result as? [String: Any] else { return }
            guard let detailes = json["storeDetailes"] as? [String: Any] else { return }
            
            let messageArray = NSMutableArray()
            messageArray.add(detailes["store_name"]!)
            messageArray.add(detailes["address"]!)
            messageArray.add(detailes["bank_name"]!)
            messageArray.add(detailes["bank_account"]!)
            messageArray.add(detailes["contact"]!)
            if let value = detailes["contact2"] {
                let v = value as! String
                messageArray.add(v)
            } else {
                messageArray.add("")
            }
            messageArray.add(detailes["license_code"]!)
            
            let str = detailes["license_img_url"] as! String
            let url = URL(string: Base_url + str)
            let imagedata = NSData(contentsOf: url! as URL)
            let image = imagedata != nil ? UIImage(data: imagedata! as Data) : nil
            
            let str2 = detailes["avatar_img_url"] as! String
            let url2 = URL(string: Base_url + str2)
            let imageadata2 = NSData(contentsOf: url2! as URL)
            let image2 = imageadata2 != nil ? UIImage(data: imageadata2! as Data) : nil
            
            let imageArray = NSMutableArray()
            let array = json["storeAuditImgDetailes"] as? NSArray
            
            var i = 0
            for obj in array! {
                let tempDict = obj as! NSDictionary
                let tempUrl = tempDict["img_url"] as! String
                let image_url = NSURL(string: Base_url + tempUrl)
                let tempData = NSData(contentsOf: image_url! as URL)
                let tempImage = tempData != nil ? UIImage(data: tempData! as Data) : nil
                if tempImage == nil {
                    i += 1
                }
                imageArray.add(tempImage ?? UIImage())
            }
            
            let reviewWeVc = ReviewWeViewController()
            reviewWeVc.realArray = messageArray
            reviewWeVc.zhizhaoImage = image
            reviewWeVc.liebiaoImage = image2
            
            if i != 0 {
                ProgressHUD.alert(message: "图片未正常显示, 请重试", on: reviewWeVc)
            }
            
            if imageArray.count < 6 {
                reviewWeVc.imageArray = ["", "", "", "", "", ""]
                for i in 0..<imageArray.count {
                    reviewWeVc.imageArray?.replaceObject(at: i, with: imageArray[i])
                }
            } else {
                reviewWeVc.imageArray = imageArray
            }
            
            let nav = UINavigationController(rootViewController: reviewWeVc)
            ProgressHUD.dismiss()
            dvc.present(nav, animated: true, completion: nil)
        }
        
    }
    
}
